package netWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王圆豪
 * Date: 2025-05-17
 * Time: 21:52
 */
public class TcpEchoClient1 {
    private Socket socket = null;

    //因为TCP是有连接的，socket会维护连接状态
    // ，所以不需要额外创建成员变量保存目的端口和目的地址
    public TcpEchoClient1(String serverIP, int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);
    }

    public void start() throws IOException {
        System.out.println("客户端已开启！");
        Scanner sc = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                //读取用户输入数据
                String request = sc.next();
                if (request.equals("byte")){
//                    socket.close();
                    break;
                }
                outputStream.write(request.getBytes());
                //获取服务器响应
                byte[] data = new byte[4096];
                int n = inputStream.read(data);
                String reponse = new String(data,0,n);
                //打印
                System.out.println(reponse);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient1 client1 = new TcpEchoClient1("127.0.0.1", 9090);
        client1.start();
    }
}
